Skip to main content

Declarative Control Flow

Component bodies, modifier bodies, and template bodies support a declarative form of if and for. Unlike their imperative counterparts, declarative if and for produce components as output rather than executing side effects — each component expression in the body contributes automatically to the result without any manual accumulation.

Declarative if

Use declarative if to conditionally include one or more components.

component Badge {
@property count: Int
@property show_label: Bool

if self.show_label {
Text("Count:")
}
Text("\{self.count}")
}

else and elseif are also supported:

component Status {
@property value: Int

if self.value > 100 {
Text("High")
} elseif self.value > 50 {
Text("Medium")
} else {
Text("Low")
}
}

Declarative for

Use declarative for to produce a component for each element in a collection.

component NameList {
@property names: [String]

for name in self.names {
Text(name)
}
}

Siblings and Containers

All components produced by a declarative body — whether from direct expressions, if, or for — appear as direct siblings in the parent container. No intermediate wrapper is inserted.

import { VStack, Text } from ui

component Group {
@property include_extra: Bool

Text("First")
Text("Second")
if self.include_extra {
Text("Third")
}
}

// All texts are direct children of VStack,
// each separated by its spacing of 8.
export var main: Component = VStack(spacing: 8) {
Group(include_extra: true)
}

Availability

Declarative if and for are available in:

  • Component bodies
  • Modifier bodies
  • Template bodies (including trailing blocks and template literals)

They are not available in imperative code such as function bodies or class methods. See Control Flow for the imperative equivalents.